package dxn.nl.file.api;

import dxn.boot.common.entity.BaseResult;
import dxn.nl.file.biz.manager.MinIoImageManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/file/upload")
@Tag(name = "文件上传")
public class FileUploadControl {

    @Resource
    private MinIoImageManager minIoImageManager;

    @Operation(summary = "通用文件上传")
    @PostMapping("/uploadBasicFile")
    public BaseResult uploadBasicFile(@RequestParam("file") MultipartFile file
            , @RequestParam(value = "bucketName",required = false)String bucketName
            , @RequestParam("mode")String mode)
    {
        try{
            if (file.isEmpty()) {
                log.info("上传文件 文件内容为空");
                return BaseResult.fail("上传文件不能为空");
            }
            log.info("上传文件{}",file.getName());

            if(StringUtils.isBlank(bucketName))
            {
                bucketName="cms";
            }

            if(!minIoImageManager.existBucketName(bucketName))
            {
                log.info("上传文件失败 存储桶 {} 不存在",bucketName);
                return BaseResult.fail("上传文件失败 存储桶 {} 不存在,请联系运维人员解决",bucketName);
            }

            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDateTime time = LocalDateTime.now();

            if(StringUtils.isBlank(mode))
            {
                mode="other";
            }

            String imagePath = mode+"/"+df.format(time)+"/"+UUID.randomUUID().toString().replace("-","")+file.getName();

            //上传文件
            String result = minIoImageManager.saveFile(bucketName,file,imagePath);
            if(StringUtils.isBlank(result))
            {
                return BaseResult.success();
            }
            log.info("上传文件失败，存储失败： {} ",result);
            return BaseResult.fail("上传失败"+result);
        }
        catch (Exception ex)
        {
            log.error("", ex);
            return BaseResult.fail(ex.getMessage());
        }
    }
}
